<template>
    <h2>生产计划添加</h2>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="form.addDto" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <table style="width: 100%; border: 1px solid #ccc">
            <tr>
                <td colspan="3" style="background-color: grey">
                    <h3 style="color: aliceblue">基本信息</h3>
                    <hr />
                </td>
            </tr>
            <tr>
                <td>
                    <el-form-item label="关联预生产计划" prop="vendorId">
                        <el-input v-model="form.preProductionPlanname" style="width: 300px"
                            @dblclick="dialogVisibleyjh = true" placeholder="双击选择生产计划" />
                    </el-form-item>
                </td>
                <td>
                    <el-form-item label="单据主题" prop="vendorId">
                        <el-input v-model="form.addDto.pPlanName" style="width: 300px" />
                    </el-form-item>
                </td>
                <td>
                    <el-form-item label="单据编号" prop="vendorId">
                        <el-input v-model="form.addDto.ppDocumentNumber" style="width: 300px" :disabled="true" />
                    </el-form-item>
                </td>
            </tr>
            <tr>
                <td>
                    <el-form-item label="自动生成订单" prop="resource">
                        <el-radio-group v-model="form.addDto.whetherautomatic">
                            <el-radio :value="true" checked="true" size="large">是</el-radio>
                            <el-radio :value="false" size="large">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </td>
                <td>
                    <el-form-item label="关联销售合同" prop="vendorId">
                        <el-input v-model="form.saleContractName" style="width: 300px" @dblclick="dialogVisible2 = true"
                            placeholder="双击选择销售合同" />
                    </el-form-item>
                </td>
                <td>

                </td>
            </tr>
            <tr>
                <td colspan="3">
                    <el-form-item label="备注" prop="desc">
                        <el-input v-model="form.addDto.pPlanSmark" type="textarea" />
                    </el-form-item>
                </td>
            </tr>
        </table>
        <br />
        <div style="height: 50px;">
            <el-button round @click="addhang()">新增行</el-button>
        </div>

        <!-- 产品表格 -->
        <table border="1" style="border-collapse: collapse; width: 1000px; height: 40px;">
            <thead>
                <tr>
                    <th><input type="checkbox" style="width: 30px;" />
                    </th>
                    <th style="height: 40px;">序号</th>
                    <th>产品名称</th>
                    <th>产品编号</th>
                    <th>规格型号</th>
                    <th>单位</th>
                    <th>数量</th>
                    <th>物料清单</th>
                    <th>计划开工日期</th>
                    <th>计划完工日期</th>
                    <th>交货日期</th>
                    <th>备注</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item, index) in check" :key="index">
                    <td><input type="checkbox" v-model="ids" style="width: 30px;width: 100%;" @click="huoqu" /></td>
                    <td style=" text-align: center;">{{ index + 1 }}</td>
                    <td>
                        <input v-model="item.pName" type="text" placeholder="双击选择产品"
                            style="height: 40px; width: 150px;text-align: center;" @dblclick="dialogVisible = true" />
                    </td>
                    <td>
                        <input v-model="item.pNumber" type="text" style="height: 40px; width: 150px;text-align: center;"
                            :disabled="true" />
                    </td>
                    <td>
                        <input v-model="item.pSpec" type="text" style="height: 40px; width: 150px;text-align: center;"
                            :disabled="true" />
                    </td>
                    <td>
                        <input v-model="item.pUnit" type="text" style="height: 40px; width: 150px;text-align: center;"
                            :disabled="true" />
                    </td>
                    <td>
                        <input v-model="item.ppNum" type="text" style="height: 40px; width: 150px;text-align: center;"
                            @change="sumRPNum" />
                    </td>
                    <td>
                        <input v-model="form.mSubjects" type="text" placeholder="双击物料清单"
                            style="height: 40px; width: 150px;text-align: center;" @dblclick="dialogVisibleqd = true" />
                    </td>
                    <td>
                        <el-date-picker v-model="item.ppAppStartDate" type="date" aria-label="Pick a date"
                            placeholder="Pick a date" style="height: 40px; width: 150px;text-align: center;" />
                    </td>
                    <td>
                        <el-date-picker v-model="item.ppAppEndDate" type="date" aria-label="Pick a date"
                            placeholder="Pick a date" style="height: 40px; width: 150px;text-align: center;" />
                    </td>
                    <td>
                        <el-date-picker v-model="item.ppReleDate" type="date" aria-label="Pick a date"
                            placeholder="Pick a date" style="height: 40px; width: 150px;text-align: center;" />
                    </td>
                    <td>
                        <input v-model="item.pProuctSmark" type="text"
                            style="height: 40px; width: 150px;text-align: center;" />
                    </td>
                </tr>
            </tbody>
        </table>
        &nbsp;
        <table border="1" style="border-collapse: collapse; width: 1000px; height: 40px;">
            <tr>
                <td colspan="7">
                    <el-form-item label="数量合计">
                        <el-input v-model="form.sumnums" style="height: 40px; width: 200px;text-align: center;"
                            :disabled="true" />
                    </el-form-item>
                </td>
            </tr>
        </table>
        <!-- 产品名称弹框 -->
        <el-dialog v-model="dialogVisible" title="产品名称选择" width="1000" style="height: 700px;"
            :before-close="handleClose">
            <span></span>
            <template #footer>
                <el-row>
                    <el-col :span="4">
                        <el-tree style="max-width: 600px" :data="VendorType" :props="defaultProps"
                            default-expand-all="true" />
                    </el-col>
                    <el-col :span="20">
                        <el-table :data="productlist" border style="width: 100%"
                            @selection-change="handleSelectionChange">
                            <el-table-column type="selection" width="55" />
                            <el-table-column prop="pName" label="产品名称" align="center" />
                            <el-table-column prop="pNumber" label="产品编号" align="center" />
                            <el-table-column prop="pUnit" label="规格型号" align="center" />
                        </el-table>
                    </el-col>
                </el-row>
                <el-button type="primary" @click="dialogVisible = false">
                    保存
                </el-button>
            </template>
        </el-dialog>

        <!-- 物料清单弹框 -->
        <el-dialog v-model="dialogVisibleqd" title="物料清单选择" width="1000" style="height: 700px;"
            :before-close="handleClose">
            <span></span>
            <template #footer>
                <el-row>
                    <el-col :span="20">
                        <el-table :data="qdlist" border style="width: 100%" @selection-change="handleSelectionChanges">
                            <el-table-column type="selection" width="55" />
                            <el-table-column prop="materialNode" label="清单编号" align="center" />
                            <el-table-column prop="mSubject" label="清单主题" align="center" />
                            <el-table-column prop="addName" label="添加人员" align="center" />
                        </el-table>
                    </el-col>
                </el-row>
                <el-button type="primary" @click="dialogVisibleqd = false">
                    保存
                </el-button>
            </template>
        </el-dialog>


        <!-- 预生产计划弹框 -->
        <el-dialog v-model="dialogVisibleyjh" title="预生产计划选择" width="1000" style="height: 700px;"
            :before-close="handleClose">
            <span></span>
            <template #footer>
                <el-row>
                    <el-col :span="20">
                        <el-table :data="tableData" border style="width: 100%"
                            @selection-change="handleSelectionChangesyu">
                            <el-table-column type="selection" width="55" />
                            <el-table-column prop="ppDocuNumber" label="预生产计划编号" align="center" />
                            <el-table-column prop="ppName" label="预生产计划主题" align="center" />
                            <el-table-column prop="ppNumTotal" label="计划数量合计" align="center" />
                            <el-table-column prop="ppGeneratedNum" label="已计划数量合计" align="center" />
                        </el-table>
                    </el-col>
                </el-row>
                <el-button type="primary" @click="dialogVisibleyjh = false">
                    保存
                </el-button>
            </template>
        </el-dialog>

        <!-- 销售合同弹框 -->
        <el-dialog v-model="dialogVisible2" title="销售合同" width="1000" style="height: 400px;color:black">
            <span></span>
            <template #footer>
                <el-table :data="showGet" border style="width: 100%" @selection-change="SaleSelection">
                    <el-table-column type="selection" width="55px" />
                    <el-table-column type="index" label="序号" width="55px" />
                    <el-table-column prop="sCcontractNumber" label="合同编号" width="180" />
                    <el-table-column prop="contractTopic" label="合同主题" width="180" />
                    <el-table-column prop="relevancyIName" label="关联项目" width="180" />
                    <el-table-column prop="clientName" label="客户名称" width="180" />
                    <el-table-column prop="scAgencyDate" label="签约日期" width="180" />
                    <el-table-column prop="scNum" label="数量合计" />
                    <el-table-column prop="scSalespeople" label="销售人员" width="180" />
                    <el-table-column prop="scTax" label="税额合计" width="180" />
                    <el-table-column prop="sCcontractPrice" label="合同总额" width="180" />
                    <el-table-column prop="scPreferentialPrice" label="优惠额度" width="180" />
                    <el-table-column prop="preferentialPrice" label="优惠后总额" width="180" />
                    <el-table-column label="操作" width="180" />
                </el-table>
                <el-button type="primary" @click="dialogVisible2 = false">
                    保存
                </el-button>
            </template>
        </el-dialog>

        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                保存
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
    </el-form>
</template>
<script setup lang="ts">
import { onMounted, ref, reactive, computed } from "vue";
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const locationOptions = ["Home", "Company", "School"];
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import http from '../../../http.js'
const dialogVisible = ref(false)
const dialogVisibleqd = ref(false)
const dialogVisibleyjh = ref(false)
const dialogVisible2 = ref(false)
const route = useRoute();
const router = useRouter();
const form = reactive({
    sumnums: 0,//数量合计
    preProductionPlanname: '',
    mSubjects: '',
    saleContractName: '',//销售合同
    "addDto": {
        "preProductionPlanId": '',
        "ppDocumentNumber": "",
        "pPlanName": "",
        "ppTotalQuantity": '',
        "preProductionState": 2,
        "saleContractId": '',
        "whetherautomatic": '',
        "pPlanSmark": "",
        "adddtos": [
            {
                "ppDocumentNumber": "",
                "productId": '',
                "pNumber": "",
                "pName": "",
                "pSpec": "",
                "pUnit": "",
                "ppNum": '',
                "mSubject": "",
                "ppAppStartDate": "",
                "ppAppEndDate": "",
                "ppReleDate": "",
                "pProuctSmark": ""
            }
        ]
    }
})
//随机数
const generateRandomNumber = () => {
    const a = Math.floor(100000 + Math.random() * 900000); // 生成一个 6 位的随机数
    sessionStorage.setItem('Vendor', JSON.stringify(a));
    form.addDto.ppDocumentNumber = String(a);
}
//生命周期函数钩
onMounted(() => {
    generateRandomNumber(); //生成随机数
    ProductList();  //显示产品列表
    getVendorType(); //显示供应商类型
    MaterialShow(); //显示物料清单
    GetShowTime();//显示预生产计划
    Show();//显示销售合同
})
const ids = ref([])
//点击新增行
const check = ref([])
const addhang = () => {
    check.value.push({
        pName: '',//产品名称
        pNumber: "",//产品编号
        pSpec: "",//产品规格
        pUnit: "",//产品单位
        ppNum: "",//计划数量
        mSubject: "",//物料清单
        ppAppStartDate: "",//计划开始时间
        ppAppEndDate: "",//计划结束时间
        ppReleDate: "",//交货日期
        pProuctSmark: "",//备注
        productId: '',//产品编号
    });
}

//#region  产品名称弹框
//显示供应商中的供应商类别树形
var VendorType = ref([]);
const getVendorType = () => {
    axios.get(http.zblnb + '/cg/api/Vendor/ProductTypeSelect').then(res => {
        if (res.data.code == 0) {
            VendorType.value = res.data.data
        }
        console.log(VendorType.value)
    })
}

const productPage = reactive({
    pindex: 1,
    psize: 100,
    pageLast: 0,
    sumCount: 0,
    PName: "",
    PNumber: "",
})
//显示产品列表
const productlist = ref([])
const ProductList = () => {
    axios.get(http.zblnb + '/cg/api/ProcurementReturn/GetProductList', {
        params: {
            pindex: productPage.pindex,
            psize: productPage.psize,
            PName: productPage.PName || "",
            PNumber: productPage.PNumber || "",
            ProductTypeId: 0
        }
    })
        .then(res => {
            productlist.value = res.data.data.list
            productPage.sumCount = res.data.data.sumCount;
            productPage.pageLast = res.data.data.pageLast
            console.log(res.data)
        })
}

//选中的产品名称
const handleSelectionChange = (val: any) => {
    check.value = val
    console.log(val)
    console.log(check.value[0].pName)
}

//#endregion


//点击复选框获取选中的值
const selectedRows = ref([])
const huoqu = () => {
    if (ids.value) {
        selectedRows.value = check.value.filter(item => item.productId);
    }
    console.log(selectedRows.value)
}
//#region 物料清单弹窗
const materialPage = reactive({
    pageIndex: 1,
    pageSize: 10,
    totalCount: 0,
    pageCount: 0,
    MSubject: '',
    MaterialNode: 0,
    MPName: '',
    AddName: '',
    STime: '',
    LTime: '',
    Office_Id: 1,
})
//显示产品列表
const qdlist = ref([])
const MaterialShow = () => {
    console.log(materialPage)
    axios.get(http.zblnb + '/sc/api/Material/MaterialShow', {
        params: {
            Office_Id: materialPage.Office_Id,
            pageIndex: materialPage.pageIndex,
            pageSize: materialPage.pageSize,
            MSubject: materialPage.MSubject,
            MaterialNode: materialPage.MaterialNode,
            MPName: materialPage.MPName,
            AddName: materialPage.AddName,
            STime: materialPage.STime,
            LTime: materialPage.LTime
        }

    }).then(res => {
        console.log(res.data.data.list)
        qdlist.value = res.data.data.list
        materialPage.totalCount = res.data.data.totalcount
        materialPage.pageCount = res.data.data.pagecount
    })
}
const check1 = ref([])
const handleSelectionChanges = (val: any) => {
    check1.value = val
    console.log(check1.value)
    console.log(check1.value[0].mSubject)
    form.mSubjects = check1.value[0].mSubject
}
//#endregion


//#region 预生产计划弹窗
const Page = ref({
    PageIndex: 1,
    PageSize: 10,
    listcount: 0,
    pagecount: 0
})
const forms = reactive({
    PPState: '',
    PPDocuNumber: '',
    PPName: '',
    PPType: '',
})
const tableData = ref([])
const GetShowTime = () => {
    debugger
    axios.get(http.zblnb + "/sc/api/PreProduction/PreProductionSelectShow", {
        params: {
            PPState: forms.PPState,
            PPDocuNumber: forms.PPDocuNumber,
            PPName: forms.PPName,
            PPType: forms.PPType,
            PageIndex: Page.value.PageIndex,
            PageSize: Page.value.PageSize
        }
    }).then((res) => {
        tableData.value = res.data.data.list;
        Page.value.listcount = res.data.data.totalcount;
        Page.value.pagecount = res.data.data.pagecount;
        console.log(tableData.value)
    })
}
const check2 = ref([])
const handleSelectionChangesyu = (val: any) => {
    check2.value = val
    console.log(check2.value)
    console.log(check2.value[0])
    form.preProductionPlanname = check2.value[0].ppName
    form.addDto.preProductionPlanId = check2.value[0].preProductionId
}
//#endregion

//#region  销售合同



const pagesale = reactive({
    PageIndex: 1,
    PageSize: 10,
    totalCount: 0,
    pageCount: 0
})
var showGet = ref([])
const Show = () => {
    axios.get(http.zblnb + '/cw/api/SaleContract/ShowStateSalesReturn', {
        params: {
            PageIndex: pagesale.PageIndex,
            PageSize: pagesale.PageSize,
        }
    }).then((res) => {
        if (res.data.code == 200) {
            console.log(res.data.data)
            showGet.value = res.data.data.list
            pagesale.totalCount = res.data.data.lcount
            pagesale.pageCount = res.data.data.pcount

        }
    })
}

const SaleSelection = (val: any) => {
    ids.value = val
    ids.value.forEach(item => {
        form.contractTopic = item.contractTopic
    })
    form.saleContractName = ids.value[0].contractTopic
    form.addDto.saleContractId = ids.value[0].contractId
}

//#endregion



//取消
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    location.reload();
}

//数量合计
//输入数量change事件
const sumRPNum = (sum: number) => {
    form.sumnums += Number(sum.srcElement.__vnode.dirs[0].value);
}

//添加预生产计划
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            var model = {
                preProductionPlanId: form.addDto.preProductionPlanId,
                ppDocumentNumber: form.addDto.ppDocumentNumber,
                pPlanName: form.addDto.pPlanName,
                ppTotalQuantity: String(form.sumnums),
                preProductionState: form.addDto.preProductionState,
                saleContractId: form.addDto.saleContractId,
                whetherautomatic: form.addDto.whetherautomatic,
                pPlanSmark: form.addDto.pPlanSmark,
                adddtos: selectedRows.value.map(item => ({
                    pNumber: item.pNumber,
                    pName: item.pName,
                    pSpec: item.pSpec,
                    pUnit: item.pUnit,
                    ppNum: item.ppNum,
                    mSubject: form.mSubjects,
                    ppAppStartDate: item.ppAppStartDate,
                    ppAppEndDate: item.ppAppEndDate,
                    ppReleDate: item.ppReleDate,
                    pProuctSmark: item.pProuctSmark,
                    productId: item.productId
                }))
            }

            console.log(model)
            form.addDto.adddtos = form.addDto.adddtos.filter((item) => item.ppNum != '')
            axios.post(http.zblnb + '/sc/api/ProductionPlan/AddProductionPlan', {
                addDto: model
            })
                .then(res => {
                    console.log(res.data)
                    if (res.data.data > 0) {
                        ElMessage.success('添加成功');
                        router.push('/ShowProductionPlan');
                    }
                    else {
                        ElMessage.error('添加失败');
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}

if (route.query.ids != '') {
    axios.get(http.zblnb + '/sc/api/PreProduction/PreProductionFan?PreProductionId=' + route.query.ids).then((res) => {
        // form.preProductionPlanname=res.data.data[0].ppName
        console.log(res.data.data)
        form.preProductionPlanname = res.data.data.ppName
        console.log(check.value)
        check.value = res.data.data.fanDto
        form.sumnums = res.data.data.ppNumTotal
        console.log(res.data.data.fanDto[0].pPsNum)
        check.value[0].ppNum = res.data.data.fanDto[0].pPsNum
        form.addDto.preProductionPlanId = res.data.data.preProductionId
    })
}
</script>
<style>
table {
    width: 100%;
    /* 可选：设置表格宽度 */
    border-collapse: collapse;
    /* 防止单元格之间的间隔 */
}

td {
    text-align: center;
    /* 水平居中 */
    vertical-align: middle;
    /* 垂直居中 */
    border: 1px solid #ddd;
    /* 添加边框用于可视化 */
    padding: 10px;
    /* 单元格内边距 */
}
</style>